const KoaRouter = require('koa-router')
const userService = require('../service/userService')
const code = require('../common/code')
const auth = require('../middleware/auth')

const router = new KoaRouter()

//用户获得本店所有EDP
router.get('/storeUserList', auth(['EDP']), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await userService.getStoreUserList(ctx.session.user.store_id))
})
//用户修改密码
router.patch('/password', auth(null), async ctx => {
    const { oldPassword, newPassword, confirmPassword } = ctx.request.body
    if (!/^.{5,20}$/.test(oldPassword)) {
        ctx.body = code.getCode(code.VALIDATE_ERROR, '原密码的长度为 5 到 20 个字符')
    } else if (!/^.{5,20}$/.test(newPassword)) {
        ctx.body = code.getCode(code.VALIDATE_ERROR, '新密码的长度为 5 到 20 个字符')
    } else if (!/^.{5,20}$/.test(confirmPassword)) {
        ctx.body = code.getCode(code.VALIDATE_ERROR, '确认密码的长度为 5 到 20 个字符')
    } else if (newPassword !== confirmPassword) {
        ctx.body = code.getCode(code.VALIDATE_ERROR, '2次密码输入不一致')
    } else if (newPassword === oldPassword) {
        ctx.body = code.getCode(code.VALIDATE_ERROR, '新密码与原密码相同')
    } else {
        const user = await userService.getUserByIdForPassword(ctx.session.user.id)
        if (user && user.enable && user.comparePassword(oldPassword)) {
            userService.updatePassword(newPassword, ctx.session.user.id)
            delete ctx.session.user
            ctx.body = code.getCode(code.SUCCESS)
        } else {
            ctx.body = code.getCode(code.PASSWORD_ERROR)
        }
    }
})
//登陆用户修改信息
router.put('/user', auth(null), async ctx => {
    await userService.updateInformation(ctx.request.body, ctx.session.user.id)
    ctx.body = code.getCode(code.SUCCESS)
})
//用户获得自己的信息
router.get('/user', auth(null), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await userService.getUserById(ctx.session.user.id))
})

module.exports = router
